﻿// AmazonService.cs
//

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Xml.Linq;

namespace BookClub.Web.WebServices.Amazon {

    internal sealed class AmazonService : IBookStoreService {

        private const string QueryUriFormat = "Service=AWSECommerceService&Version=2009-03-31&Operation=ItemLookup&ItemId={0}&ResponseGroup=Similarities";
        private const string ServiceDomain = "ecs.amazonaws.com";

        public string[] FindSimilarProducts(string asin) {
            string[] similarIDs = null;

            try {
                similarIDs = FindSimilarProductsCore(asin);
            }
            catch {
            }

            if (similarIDs == null) {
                // NOTE: This is a set of hard-coded IDs for demo purposes, in case the
                //       Amazon service fails, or access key/secret key pair haven't been
                //       set up etc.
                similarIDs = new string[] { "0321545613", "0321440064", "059652028X", "032143482X", "0321554167" };
            }

            return similarIDs;
        }

        private string[] FindSimilarProductsCore(string asin) {
            string[] similarIDs = null;

            SignedRequestHelper signer =
                new SignedRequestHelper(ConfigurationManager.AppSettings["amazonAccessKey"],
                                        ConfigurationManager.AppSettings["amazonSecretKey"],
                                        ServiceDomain);

            string url = signer.Sign(String.Format(QueryUriFormat, asin));
            Uri searchUri = new Uri(url, UriKind.Absolute);

            WebClient webClient = new WebClient();
            string xml = webClient.DownloadString(searchUri);

            if (String.IsNullOrEmpty(xml) == false) {
                // Remove the default xmlns, simply because it simplifies the node names
                // we use in the XLINQ statement next.
                xml = xml.Replace(@"xmlns=""http://webservices.amazon.com/AWSECommerceService/2009-03-31""", String.Empty);
                XDocument xdoc = XDocument.Parse(xml);

                IEnumerable<string> idsQuery =
                    from item in xdoc.Descendants("SimilarProduct")
                    where item.HasElements
                    select item.Element("ASIN").Value;

                similarIDs = idsQuery.ToArray();
            }

            return similarIDs;
        }

        public bool IsValidASIN(string asin) {
            if (asin.StartsWith("abcd", StringComparison.OrdinalIgnoreCase)) {
                return false;
            }
            return true;
        }
    }
}
